package manager

import (
	"errors"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/manager"
	managerReq "gitcode.com/G-YT/ANN/server/model/manager/request"
	managerRes "gitcode.com/G-YT/ANN/server/model/manager/response"
	"gitcode.com/G-YT/ANN/server/model/user"
	"gorm.io/gorm"
	"time"
)

type MessageRemindService struct {
}

// SaveMessageRemind 创建消息提醒记录
// Author [g-qs](https://github.com/g-qs)
func (mrService *MessageRemindService) SaveMessageRemind(mr *manager.MessageRemind) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 判断今日是否已创建对该用户的消息提醒
		today := time.Now().Format("2006-01-02")
		tomorrow := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
		var messageRemind manager.MessageRemind
		var hm manager.FdHealthManager
		err = tx.Where("user_id = ? and created_at BETWEEN ? AND ?", mr.UserID, today, tomorrow).First(&messageRemind).Error
		if messageRemind.ID != 0 {
			if messageRemind.Status == true {
				return errors.New("用戶已評分，不可更改消息提醒")
			} else {
				if err = tx.Model(&manager.MessageRemind{}).Where("user_id = ? and created_at BETWEEN ? AND ?", mr.UserID, today, tomorrow).Update("remind", mr.Remind).Error; err != nil {
					return err
				}
			}

		} else {
			if cErr := tx.Create(mr).Error; cErr != nil {
				return cErr
			}
		}
		if hmErr := tx.Where("hm_id", mr.HmID).First(&hm).Error; hmErr != nil {
			return hmErr
		}
		*hm.ServedNum += 1
		if uhm := tx.Model(&manager.FdHealthManager{}).Where("hm_id", mr.HmID).Update("served_num", *hm.ServedNum).Error; uhm != nil {
			return uhm
		}
		return err
	})
}

// DeleteMessageRemind 删除消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) DeleteMessageRemind(id string) (err error) {
	err = global.GVA_DB.Delete(&manager.MessageRemind{}, "id = ?", id).Error
	return err
}

// DeleteMessageRemindByIds 批量删除消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) DeleteMessageRemindByIds(ids []string) (err error) {
	err = global.GVA_DB.Delete(&[]manager.MessageRemind{}, "id in ?", ids).Error
	return err
}

// UpdateMessageRemind 更新消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) UpdateMessageRemind(mr manager.MessageRemind) (err error) {
	return global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		var messageRemind manager.MessageRemind
		err = tx.Where("id = ?", mr.ID).First(&messageRemind).Error
		var healthManager manager.FdHealthManager
		if hmerr := tx.Where("hm_id = ?", messageRemind.HmID).First(&healthManager).Error; hmerr != nil {
			return hmerr
		}
		if messageRemind.Status == true {
			return errors.New("已評分，請勿重複操作")
		}
		if mderr := global.GVA_DB.Model(&manager.MessageRemind{}).Where("id = ?", mr.ID).Updates(map[string]interface{}{"score": mr.Score, "status": true}).Error; mderr != nil {
			return mderr
		}
		score := mr.Score + healthManager.Score
		if herr := tx.Model(&healthManager).Where("hm_id = ?", messageRemind.HmID).Update("score", score).Error; herr != nil {
			return herr
		}
		return err
	})

}

// GetMessageRemind 根据id获取消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) GetMessageRemind(userID string) (info managerRes.MessageRemind, err error) {
	var mr manager.MessageRemind
	today := time.Now().Format("2006-01-02")
	tomorrow := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
	err = global.GVA_DB.Where("user_id = ? and created_at BETWEEN ? AND ?", userID, today, tomorrow).First(&mr).Error
	var userinfo user.User
	err = global.GVA_DB.Where("id = ?", userID).Preload("HealthManager").First(&userinfo).Error
	info = managerRes.MessageRemind{
		ID:        mr.ID,
		HmID:      mr.HmID,
		Name:      userinfo.HealthManager.Name,
		HeaderImg: userinfo.HealthManager.HeaderImg,
		Remind:    mr.Remind,
		UserID:    mr.UserID,
		Status:    mr.Status,
		Score:     mr.Score,
	}
	return
}

// GetMessageRemindInfoList 分页获取消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) GetMessageRemindInfoList(info managerReq.MessageRemindSearch) (list []manager.MessageRemind, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&manager.MessageRemind{})
	var mrs []manager.MessageRemind
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&mrs).Error
	return mrs, total, err
}

// GetMessageRemindRecord 分页获取消息提醒记录
// Author [piexlmax](https://github.com/piexlmax)
func (mrService *MessageRemindService) GetMessageRemindRecord(info manager.MessageRemind) (list []manager.MessageRemind, err error) {
	// 获取当前时间的零点
	now := time.Now()
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	// 计算一周前的时间
	oneWeekAgo := today.AddDate(0, 0, -7)
	err = global.GVA_DB.Model(&manager.MessageRemind{}).Where("user_id = ? AND created_at >= ? AND created_at < ?", info.UserID, oneWeekAgo, today).Find(&list).Error
	return
}
